package com.dondedesigns.eh.persistence.dao;

import java.util.List;

import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;

import com.dondedesigns.eh.persistence.ApprovedStatus;
import com.dondedesigns.eh.persistence.User;

public class UserDAO extends GenericDAO<User> {
	
	public User getUser (String username, String password) {
		Session s = (Session)getEntityManager().getDelegate();
		User user = (User) s.createCriteria(User.class)
			.add(Restrictions.eq("username", username))
			.add(Restrictions.eq("password", password))
			.uniqueResult();
		return user;
	}
	
	public boolean userExists (User user) {
		return exists(user);
	}
	
	public boolean emailExists (User user) {
		User tempUser = getUserByEmail(user);
		return (tempUser != null);
	}
	
	public User getUserByEmail(User user) {
		Session s = (Session)getEntityManager().getDelegate();
		User tempUser = (User) s.createCriteria(User.class)
			.add(Restrictions.eq("email", user.getEmail()))
			.setFlushMode(FlushMode.MANUAL)
			.uniqueResult();
		return tempUser;
	}

	public List<User> select() {
		return super.select(User.class);
		
	}
	
	@SuppressWarnings("unchecked")
	public List<User> selectActiveUsers() {
		Session s = (Session)getEntityManager().getDelegate();
		List<User> activeUsers = s.createCriteria(User.class)
			.add(Restrictions.eq("approvedStatus", ApprovedStatus.APPROVED))
			.addOrder(Order.asc("username"))
			.list();
		return activeUsers;

	}
	
	@SuppressWarnings("unchecked")
	public List<User> selectUnauthorizedUsers() {
		Session s = (Session)getEntityManager().getDelegate();
		List<User> unauthorizedUsers = s.createCriteria(User.class)
			.add(Restrictions.eq("approvedStatus", ApprovedStatus.PENDENT))
			.addOrder(Order.asc("username"))
			.list();
		return unauthorizedUsers;
	}
	
	@SuppressWarnings("unchecked")
	public List<User> selectBannedUsers() {
		Session s = (Session)getEntityManager().getDelegate();
		List<User> unauthorizedUsers = s.createCriteria(User.class)
			.add(Restrictions.eq("approvedStatus", ApprovedStatus.DENIED))
			.addOrder(Order.asc("username"))
			.list();
		return unauthorizedUsers;
	}

	public User find(Long userId) {
		return super.find (User.class, userId);
	}
	
	public boolean checkAuthorization(Long id, String page) {
		Session s = (Session)getEntityManager().getDelegate();
		User user = (User) s.createCriteria(User.class, "u")
			.add(Restrictions.eq("id", id))
			.createCriteria("role", "r")
			.add(Restrictions.eqProperty("r.id", "u.role"))
			.createCriteria("r.grantedPermissions", "p")
			.add(Restrictions.eq("p.permission", page))
			.uniqueResult();
		return (user != null);
	}
}
